<template>
    <view class="advisoryDetails backgroundSty">
        <view class="flexAverage advisoryDetails_patient">
            <view class="name">我的咨询</view>
            <view class="fr">
                <text v-if="orderDedatils.state =='1'||orderDedatils.state =='4'" style="background-color: #ffaa22;" ></text>
                <text v-if="orderDedatils.state =='2'" style="background-color: #499dff;" ></text>
                <text v-if="orderDedatils.state =='3'" style="background-color: #999999;" ></text>
                {{orderDedatils.stateText}}
            </view>
        </view>
        <view class="advisoryDetails_cnt" style="height: 300px;overflow: auto;">
            <!-- 患者 提交问题 -->
            <uni-row class="row advisoryDetails_cnt-row" >
                <uni-col span="10"><view class="patient label">我：</view></uni-col>
                <uni-col span="90"><view class="chart">{{orderDedatils.question}}</view></uni-col>
            </uni-row>
            <uni-row class="row advisoryDetails_cnt-row" v-if="orderDedatils.imglist.length >0">
                <uni-col span="10"><view class="patient label">我：</view></uni-col>
                <uni-col span="90">
                    <view class="chart clearfix">
                        <view v-for="(image,index) in orderDedatils.imglist" :for-index="index" :key="index" :for-item="image" class="chart_img">
                            <image  mode='aspectFill' :src="image" @click.native="previewImage(image,orderDedatils.imglist)"></image>
                        </view>
                    </view>
                </uni-col>
            </uni-row>
            <view v-for="item in chatList" :key="item.recordId" >
                <view v-if="item.platform ==='patient'">
                    <!-- 患者 -->
                    <uni-row class="row advisoryDetails_cnt-row" >
                        <uni-col span="10"><view class="patient label">我：</view></uni-col>
                        <uni-col span="90"><view class="chart">{{item.content}}</view></uni-col>
                    </uni-row>
                    <uni-row class="row advisoryDetails_cnt-row" v-if="item.imglist.length >0">
                        <uni-col span="10"><view class="patient label">我：</view></uni-col>
                        <uni-col span="90">
                            <view class="chart clearfix">
                                <view v-for="(image,index) in item.imglist" :for-index="index" :key="index" :for-item="image" class="chart_img">
                                    <image  mode='aspectFill' :src="image" @click.native="previewImage(image,item.imglist)"></image>
                                </view>
                            </view>
                        </uni-col>
                    </uni-row>
                </view>
                <view v-else>
                    <!-- 医生 -->
                    <uni-row class="row advisoryDetails_cnt-row" >
                        <uni-col span="80"><view class="chart doctor-chart">{{item.content}}</view></uni-col>
                        <uni-col span="20"><view class="doctor-img"><image :src="item.headPic" alt="医生头像" mode='aspectFill'></image></view></uni-col>
                    </uni-row>
                    <uni-row class="row advisoryDetails_cnt-row" v-if="item.imglist.length >0">
                        <uni-col span="80">
                            <view class="chart clearfix .doctor-chart">
                                <view v-for="(image,index) in item.imglist" :for-index="index" :key="index" :for-item="image" class="chart_img">
                                    <image  mode='aspectFill' :src="image" @click.native="previewImage(image,item.imglist)"></image>
                                </view>
                            </view>
                        </uni-col>
                        <uni-col span="20">
                            <view class="doctor-img label">
                                <image :src="item.headPic" alt="医生头像" mode='aspectFill'></image>
                            </view>
                        </uni-col>
                    </uni-row>
                </view>
            </view>
        </view>
        <view class="advisoryDetails_cnt_quiz"  v-if="orderDedatils.state =='1'||orderDedatils.state =='2'" >
            <uni-row class="advisoryDetails_cnt-row" >
                <uni-col span="80">
                    <view class="quiz_cnt">
                        <textarea v-if="modalColse" maxlength="100" :value="describe"  @blur="bindBlur" @input="bindFocus"  placeholder="请在此描述详情" />
                        <view class="quiz_cnt_text">注：超48小时订单将自动关闭</view>
                    </view>
                </uni-col>
                <uni-col span="20"  v-if="(prohibitBool ==true && orderDedatils.state =='1')||(prohibitBool ==true && orderDedatils.state =='2')"><view class="quiz_btn" @click.native="addChat">提交追问</view></uni-col>
                <uni-col span="20"  v-else><view class="quiz_btn prohibit" >提交追问</view></uni-col>
            </uni-row>
            <view class="camera">
                <image @click.native="uploadPictures" data-text="open" src="../../../static/images/weibiao.png"></image>
                <view  class="uploadImg clearfix " v-if="photosList.length>0" >
                    <view class="chart_img" v-for="(image, index) in photosList" :for-index="index" :key="index" :for-item="image">
                        <image   mode='aspectFill' :src="image"  @click.native="previewImage(image,photosList)"></image>
                        <i class="iconfont icon-close-b" @click.native="closeImg(index)"></i>
                    </view>
                </view>
                <text v-if="photosList.length==0">您可上传９张图片资料，仅解答的医生可见</text>
            </view>
        </view>
        <view class="advisoryDetails_footer">
            <uni-row class="top" @click.native="handleClick">
                <uni-col span="60">
                    <view class="label">
                       订单编号：<text>{{orderDedatils.orderNo}}</text>
                    </view>
                </uni-col>
                <uni-col span="40">
                    <view class="right" >
                        {{orderDedatils.createTime}}
                        <text :class="['iconfont',infosColse ==false?'icon-xiangxiajiantou':'icon-xiangshangjiantou']"></text>
                    </view>
                </uni-col>
            </uni-row>
            <view v-if="infosColse">
                <uni-row class="cnt" >
                    <uni-col span="60">
                        <view class="label">
                           医生信息：<text>{{doctorDedatils.doctorName}} I {{orderDedatils.deptName}} I {{doctorDedatils.titles}}</text>
                        </view>
                        <view class="label">患者信息：<text>{{patientDedatils.patientName==null?" ":patientDedatils.patientName}} I {{patientDedatils.sex=="1"?"男":"女"}} I {{patientDedatils.age==null?" ":patientDedatils.age}}</text></view>
                    </uni-col>
                    <uni-col span="40">
                        <view class="right price" >
                            {{orderDedatils.money}}元
                        </view>
                    </uni-col>
                </uni-row>
            </view>
        </view>
        <view class="advisoryDetails_footerbtn" v-if="orderDedatils.state =='1'" >
            <view @click.native="handleModal('open')">取消咨询</view>
        </view>
        <!-- 取消咨询 -->
        <view class="modal-style" :hidden="modalColse"  catchtouchmove="ture">
            <view class="closeAdvisory">
                <view class="closeAdvisory_cnt">
                    <view class="head">
                        <view>您确定取消本次咨询么？</view>
                        <view>取消后，费用将退回到您的账户。</view>
                    </view>
                </view>
                <view class="flexAverage footer">
                    <view class="fl" @click.native="handleModal('close')">再想想</view>
                    <view class="fr" @click.native="cancelAdvisory">取消咨询</view>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
    import uniRow from '@/components/uni-ui/uni-layout/row.vue'
    import uniCol from '@/components/uni-ui/uni-layout/col.vue'
    import moment from '@/common/util/moment.min.js'
    import _ from '@/common/util/underscore.js'
    import API from '@/utils/api.js'
    export default {
    	data() {
    		return {
                infosColse: false,//医生信息状态
                modalColse: true,//弹出框 状态
                keyboardBool: false,//是否触发键盘事件true是 
                doctorDedatils: {},//订单医生详情
                patientDedatils: {},//订单患者详情
                orderDedatils: {},//订单详情
                setTimer: "",//设置定时器
                orderId: "",//订单号
                chatList: [],//聊天记录数据
                chatNum: 3,//提问的次数
                prohibitBool: false,//医生没有返回，患者不能提问
                describe: "",//描述
                reason: "",//取消咨询的原因
                photosList: [],//前端显示图片地址
                picUrl: [],//提交问题事 返回后端 上传图片的地址（在上传图片按钮时后端返回的）
    		}
    	},
    	components:{
            uniRow,uniCol
    	},
    	onLoad(options) {
            this.orderId = options.orderId ||"1c1a25f1-f52e-47d1-a9a9-a6018217c40a"// "4e6ca089-b850-446e-a3ed-c7f9c369d4fb"//"df6ddbe5-7f26-49cd-81e7-e330f598768c"
            this.getOrder();
            this.getChatList();
            this.getChatNum();
            if ((this.keyboardBool === false && this.orderDedatils.state =='1')|| (this.keyboardBool === false && this.orderDedatils.state =='2')) {
                this.timerFn();
            }
    	},
        onUnload(){
            //页面卸载
            var _this = this;
            clearInterval(_this.setTimer);
        },
    	methods: {
             //订单详细
            getOrder: function () {
                //订单详情
                let params = {
                    orderId: this.orderId
                }
                API.getOrder(params).then((res) => {
                    if (res.success == true) {
                        let order = res.entity.order;
                        order.createTime = order.createTime == null ? "" : order.createTime.substring(0, 16);
                        order.deptName = order.deptName == null ? " " : order.deptName;
                        order.orderNo = order.orderNo == null ? " " : order.orderNo;
                        if (order.state === "1") {
                            order.stateText = "待回复";
                        } else if (order.state === "2") {
                            order.stateText = "待结束";
                        } else if (order.state === "3") {
                            order.stateText = "已完成";
                        } else {
                            order.stateText = "已退款";
                        }
                        if (order.picUrl == null || order.picUrl == "") {
                            order.imglist = [];
                        } else {
                            order.imglist = order.picUrl.split(",");
                        }
                        let doctor = res.entity.doctor;
                        if(doctor != null){
                            doctor.doctorName = doctor.doctorName == null ? " " : doctor.doctorName;
                            doctor.titles = doctor.titles == null ? " " : doctor.titles;
                        }
                        this.doctorDedatils = doctor,//订单医生详情
                        this.patientDedatils = res.entity.patient,//订单患者详情
                        this.orderDedatils = order;//订单详情
                    }
                })
            },
            //聊天记录数据
            getChatList: function () {
                var _this = this;
                let params = {
                    orderId: this.orderId
                }
                API.queryReply(params).then((res) => {
                    if (res.success == true) {
                        let renderData = res.entity;
                        // platform表示谁的数据 patient：患者 doctor：医生
        
                        if (renderData.length > 0) {
                            renderData = _.map(renderData, function (el) {
                                if (el.picUrl != null && el.picUrl != "") {
                                    el.imglist = el.picUrl.split(",");
                                } else {
                                    el.imglist = [];
                                }
                                el.headPic = _this.doctorDedatils==null ||  _this.doctorDedatils.headPic == null ? "https://ylz-wlzs-test.obs.cn-north-1.myhuaweicloud.com:443/1578537072939" : _this.data.doctorDedatils.headPic;
                                return el;
                            })
                            if (renderData[renderData.length - 1].platform == "doctor") {
                                this.prohibitBool = true;
                            }
                        }
                        this.chatList = renderData;
                    }
                })
            },
            //提问的次数
            getChatNum: function () {
                var _this = this;
                let params = {
                    orderId: this.orderId,
                    patientUserId: uni.getStorageSync('patientUserId')
                }
                API.getReplyCount(params).then((res) => {
                    if (res.success == true) {
                        this.chatNum = parseInt(res.entity)
                    }
                })
            },
             //键盘触发
            bindFocus: function (e) {
                this.keyboardBool = true;
                this.describe = e.detail.value;
                clearInterval(this.setTimer);
            },
            //键盘离开
            bindBlur: function (e) {
                clearInterval(this.setTimer);
                this.keyboardBool = false;
                this.describe = e.detail.value;
                this.timerFn();
            },
            //定时器
            timerFn: function () {
                let _this = this;
                let timers = setInterval(function () {
                    console.log("请求聊天执行")
                    _this.getChatList();
                    if (_this.keyboardBool === true) {
                        clearInterval(_this.setTimer);
                    }
                }, 5000)
                this.setTimer = timers;
            },
            //取消原因
            bindReason: function (e) {
                this.reason = e.detail.value;
            },
            //删除图片
            closeImg: function (index) {
                let photosList = [].concat(this.photosList);
                let picUrl = [].concat(this.picUrl);
                photosList.splice(index, 1);
                picUrl.splice(index, 1);
                this.photosList = photosList;
                this.picUrl = picUrl;
            },
            //预览图片
            previewImage: function (current,list) {
                uni.previewImage({
                    current: current, // 当前显示图片的http链接
                    urls: list // 需要预览的图片http链接列表
                })
            }, 
            //添加图片
            uploadPictures: function () {
               let _this = this;
               if (this.picUrl.length >= 9) {
                   uni.showToast({
                       title: '添加图片最多9张',
                       icon: 'none',
                       duration: 1000
                   })
                   return;
               }
               uni.chooseImage({
                   count: 3,
                   sizeType: ['original', 'compressed'],
                   sourceType: ['album', 'camera'],
                   success: function (res) {
                       let imgPaths = res.tempFilePaths;
                       for(var i=0;i<imgPaths.length;i++){
                           _this.uploadImg(_this,imgPaths[i]);
                       }
                   }
               });
            },
            // 上传图片
            uploadImg:function(mythis,imgPaths){
                let photosUrl = [], photosListshow=[];// photosUrl传给后端的地址，photosListshow前端展示的地址
                uni.uploadFile({
                    url: API.upload(), //仅为示例，非真实的接口地址 "https://twzx.191cn.com/pat-api/file/upload",//
                    filePath: imgPaths,
                    name: 'file',//这个是根据后台接口写的名字文件对应的 key，开发者在服务端可以通过这个 key 获取文件的二进制内容
                    header: {
                        'Content-Type': 'multipart/form-data'
                    },
                    formData: {
                        'file': imgPaths
                    },
                    success: function (e) {
                        let res = JSON.parse(e.data);
                        if (res.success == true) {
                            photosUrl = mythis.picUrl;
                            photosListshow = mythis.photosList;
                            photosListshow.push(imgPaths);
                            photosUrl.push(res.entity);
                            mythis.photosList = photosListshow;
                            mythis.picUrl= photosUrl;
                        }
                    }
                })  
            },
            //点击订单信息
            handleClick: function (e) {
                this.infosColse = !this.infosColse;
            },
            //取消咨询 弹出框状态
            handleModal: function (e) {
                if (e === "open") {
                    this.modalColse = false;
                } else {
                    this.modalColse = true;
                }
            },
            //取消咨询
            cancelAdvisory: function () {
                let param = {
                    reason: this.reason,
                    orderId: this.orderId
                }
                API.cancelOrder(param).then((res) => {
                    if (res.success == true) {
                        uni.showToast({
                            title: '成功取消咨询',
                            icon: 'none',
                            duration: 1000
                        })
                        this.getChatList();
                        this.getChatNum();
                        this.getOrder();
                        clearInterval(this.setTimer);
                        this.modalColse = true;
                    }
                })
            },
            //新增聊天记录 提交问题
            addChat: function () {
                console.log(this.describe, "this.data.describe.length")
                if (this.describe === "") {
                    uni.showToast({
                        title: '描述信息不能为空',
                        icon: 'none',
                        duration: 1000
                    })
                    return;
                }
                let param = {
                    orderId: this.orderId,
                    createBy: uni.getStorageSync('patientUserId'),//创建人	patientUserId
                    createName: this.patientDedatils.patientName, //创建人姓名	patientName患者姓名
                    createType: "patient",// 创建人类型	创建人类型 1患者 2医生
                    content: this.describe,
                    picUrl: this.picUrl.toString()
                }
                API.addReply(param).then((res) => {
                    if (res.success == true) {
                        uni.showToast({
                            title: "成功提交问题",
                            icon: 'none',
                            duration: 1000
                        })
                        this.describe = "";
                        this.photosList = [];
                        this.picUrl=[];
                        this.getChatList();
                        this.getChatNum();
                    } else {
                        uni.showToast({
                            title: res.message,
                            icon: 'none',
                            duration: 1000
                        })
                    }
                })
            },
    	}
    }
</script>

<style lang="scss" scoped>
   .advisoryDetails_patient{
        padding: 20rpx 0rpx 20rpx 0rpx;
        letter-spacing: 2px;
        color: #000000;
        font-size: 30rpx;
        font-weight: bold;
        border-bottom: 0.5rpx solid #efeff4;
        position: fixed;
        top:0;
        left:0;
        width: 100%;
        z-index: 3;
        background: #fff;
        .name{
            padding-left: 33rpx;
            border-left: 7rpx solid #499dff;
        }
        .fr{
            text-align: right;
            padding-right: 30rpx;
            position: relative;
        }
        .fr text{
            position: absolute;
            top:15rpx;
            right:140rpx;
            width: 8rpx;
            height: 8rpx;
            border-radius: 50%;
        }
   }
   /* 患者与医生的聊天内容 */
   .advisoryDetails_cnt{
       padding: 120rpx 0rpx 20rpx;
       background: #fff;
   }
    .advisoryDetails_cnt-row{
        font-size: 30rpx;
        .label{
            text-align: right;
            padding-left: 30rpx;
        }
        .patient{
            color: #499dff;
        	font-weight: bold;
        	letter-spacing: 2rpx;
        }
        .chart{
        	color: #000000;
            font-size: 28rpx;
            letter-spacing: 2rpx;
            padding: 22rpx;
            font-weight: bold;
            line-height: 40rpx;
            background-color: #ecf5ff;
        	border-radius: 5px;
            margin-right: 30rpx;
            margin-left: 10rpx;
            margin-bottom: 30rpx;
        }
        .doctor-chart{
            background-color: #499dff;
            color: #ffffff;
            font-size: 28rpx;
            line-height: 40rpx;
            font-weight: bold;
        }
        .doctor-img{
            margin-right: 30rpx;
            text-align: right;
            image{
                width: 73rpx;
            	height: 73rpx;
            }
        }
        .doctor-chart{
            margin-right: 0rpx;
            margin-left: 30rpx;
        }
        .chart_img{
        	float:left;
        	width:30%;
        	height:100rpx;
            margin-left: 2%;
        	margin-bottom: 20rpx;
            position: relative;
        }
        /*按钮*/
        .quiz_btn{ 
            text-align: center;
            width: 100%;
            height: 63rpx;
            color: #fff;
            line-height: 63rpx;
        }
        .quiz_text{
            letter-spacing: 2rpx;
        	color: #ff3300;
            font-size: 24rpx;
            margin: 29rpx 0;
        }
    }
    .advisoryDetails_cnt_quiz{
        background: #fff;
        .quiz_cnt  textarea{
            height: 80rpx;
        	background-color: #efeff4;
        	border-radius: 5rpx;
            letter-spacing: 2rpx;
        	color: #999999;
            padding: 22rpx 24rpx;
            font-size: 30rpx;
            width: 100%;
        }
        .quiz_cnt_text{
            letter-spacing: 2rpx;
            color: #ff3300;
            font-size: 24rpx;
            margin-left: 30rpx;
            line-height: 45rpx;
        }
        .quiz_btn{
            height: 80rpx;
            line-height: 80rpx;
            background-color: #56be2d;
        }
        .prohibit{
            background-color: #bcbcbc;
        }
        .camera{
            margin-top: 30rpx;
            padding: 0 30rpx;
            letter-spacing: 2rpx;
        	color: #999999;
            font-size: 26rpx;
            display: flex;
            image{
                width: 100rpx;
                height: 100rpx;
                margin-right: 15rpx;
                margin-bottom: 15rpx;
            }
            .uploadImg{
                flex: 1 1;
                margin-right: 15rpx;
            }
            .chart_img{
                float: left;
                width: 100rpx;
                height: 100rpx;
                margin-right: 15rpx;
                margin-left: 0;
                margin-bottom: 15rpx;
                position: relative
            }
            .chart_img i{
                position: absolute;
                top: -10rpx;
                right:-20rpx;
                color: #f00;
                background: #fff;
                border-radius: 50%;
                border:8rpx solid #fff;
            }
            text{
                flex: 1 1;
                margin-left: 28rpx;
                line-height: 100rpx;
            }
        }
    }
   /*订单信息*/
   .advisoryDetails_footer{
        font-size: 23rpx;
        color: #999999;
        padding: 20rpx 0rpx 20rpx 0rpx; 
        border-top:30rpx solid #EFEFF4;
        background: #fff;
        border-bottom:30rpx solid #EFEFF4;
        .top{
            line-height: 60rpx;
        }
        .right{
            text-align: right;
            padding-right: 20rpx;
        }
        .label{
            padding-left: 20rpx;
            padding-bottom: 20rpx;
        }
        .label text,.price{
            color: #000000;
        }
        .icon-xiangxiajiantou,.icon-xiangshangjiantou{
            font-size: 23rpx;
            margin-left: 5rpx;
        }
   }
   /* 取消咨询 按钮 */
   .advisoryDetails_footerbtn{
        width: 100%;
        background: #fff;
        text-align: right;
        padding: 35rpx;
        view{
            width: 139rpx;
        	height: 63rpx;
            display: inline-table; 
        	background-color: #ffaa22;
        	border-radius: 5rpx;
            text-align: center;
            letter-spacing: 2px;
        	color: #ffffff;
            font-size: 24rpx;
            line-height: 63rpx;
        }
   }
   /* 取消咨询 弹出框 */
    .closeAdvisory{
        position: absolute;
        top:50%;
        left:10%;
        width: 80%;
        background: #fff;
        border-radius: 8px;
        height: 280rpx; 
        z-index: 33;
        overflow:hidden;
        margin-top: -140rpx;
        .closeAdvisory_cnt{
            padding: 45rpx 30rpx 30rpx;
            .head{
                text-align: center;
                font-size: 28rpx;
            	line-height: 50rpx;
            	letter-spacing: 2rpx;
            	color: #000000;
            }
            textarea{
                width: 100%;
            	height: 170rpx;
            	background-color: #efeff4;
            	border-radius: 5rpx;
                letter-spacing: 2rpx;
            	color: #959595;
                font-size: 24rpx;
                padding: 22rpx;
                margin: 32rpx 0 30rpx;
            }
            .text{
                letter-spacing: 2rpx;
            	color: #ff3300;
                font-size: 24rpx;
            }
        }
        
        .footer{
            border-top:1rpx solid #efeff4;
            text-align: center;
            letter-spacing: 2px;
            height: 94rpx;
            font-size: 28rpx;
            font-weight: 700;
            position: relative;
            view{
                line-height: 94rpx;
            }
            .fl{
                color: #959595;
            }
            .fr{
                color: #499dff;
            }
            &:after{
                content: '';
                position: absolute;
                top:35rpx;
                left: 50%;
                width: 4rpx;
                height: 28rpx;
                background: #efeff4;
                z-index: 1;
            }
        }
    }
</style>
